﻿/// <reference path="jquery1.js" />

$$.Shell = new function () {
	var me = this;
	function emptyfunc() { }
	me._addCallback = function () { return 0; };
	 
	//获取当前经纬度
	//callback(rst,lat,lng)
	//rst:true/错误信息
	me.Gps = function (callback) { 
		if (!callback) callback = emptyfunc;
		var geo = navigator.geolocation;
		if (!geo) { callback("不能定位"); return; }
		var schema = (location.protocol || "").toLowerCase();
		if (schema !== "https" && schema !== "https:") { callback("不能定位"); return; }
		geo.getCurrentPosition(
			function (pos) {
				if (!pos) { callback("定位无效"); return; }
				pos = pos.coords;
				if (!pos) { callback("定位无效"); return; }
				callback(true, pos.latitude, pos.longitude );
			},
			function (err) {
				var msg = "定位失败";
				if (err.code === err.PERMISSION_DENIED) msg = "您拒绝定位！\n本应用需根据您的地理位置更好的提供服务";
				else if (err.code === err.POSITION_UNAVAILABLE) msg = "无法定位";
				else if (err.code === err.TIMEOUT) msg = "定位超时";
				callback(msg);
			},
			{ timeout: 10000, maximumAge: 600000 }
		);
	};

	//打开第三方地图
	me.Map = function (lat, lng, label, callback) {
		if (!label) return false;
		window.open("http://map.baidu.com/mobile/webapp/place/linesearch/foo=bar/from=place&tab=line&end=word%3D" + window.encodeURI(label) + "%26");
		return true;
	};

	me.Std = function (vid, uid) {};

	//获取当前网络状态
	//refresh：强制刷新
	//callback(rst)：回调函数
	//rst：网络状态结果
	//-1：无网络
	// 0：未知
	// 1：wlan
	// 2：数据	此状态看视频应询问
	var netState = 0, initState = false;
	me.NetState = function (refresh, callback) {
		if (!initState) {
			initState = true;
			window.addEventListener("online", me.NetState, false);
			window.addEventListener("offline", me.NetState, false);
		}
		if (!callback) callback = emptyfunc;
		if (navigator.onLine === false) {
			callback(-1);
			if (netState === -1) return;
			netState = -1;
		}
		else {
			netState = 0;
			callback(0);
			return;
		}
		$$.Dialog("访问任务兔需连接网络，请确保网络正常！", "注意", { "知道了": null });
	};

	//清空缓存
	me.ClearCache = function (callback) {
		if (!callback) callback = emptyfunc;
		$$.DB.Clear("**");
		callback(true);
	};


	//震动
	var vibrateSound = null;
	me.Vibrate = function () {
		if (navigator.vibrate) {
			navigator.vibrate([200, 200, 200]);
			return;
		}
		if (navigator.webkitVibrate) {
			navigator.webkitVibrate([200, 200, 200]);
			return;
		}
		if (!vibrateSound) vibrateSound = document.getElementById("AppVibrateSound");
		if (vibrateSound) vibrateSound.play();
	};

	//提醒声音
	//vibreate 同时震动
	var duduSound = null;
	me.Dudu = function (vibrate) {
		if (!duduSound) duduSound = document.getElementById("AppDuduSound");
		if (duduSound) duduSound.play();
		if (vibrate === true) {
			if (navigator.vibrate) navigator.vibrate([200, 200, 200]);
			else if (navigator.webkitVibrate) navigator.webkitVibrate([200, 200, 200]);
		}
	};


	var imgMime = "image/jpeg";
	function dealImage(file, option, callback) {
		if (!option) option = {};
		function calc(w, h) {
			var cw = option.width || 600;
			var ch = option.height || 0;
			if (ch <= 0) {
				if (w <= cw) return { w: w, h: h, cw: w, ch: h, x: 0, y: 0 };
				return { w: w, h: h, cw: cw, ch: h / w * cw, x: 0, y: 0 };
			}
			if (w <= cw && h <= ch) return { w: w, h: h, cw: w, ch: cw * h / w, x: 0, y: 0 };
			
			var s = w / h, cs = cw / ch, x = 0;
			if (s < cs - 0.2) {
				s = cs - 0.2;
				h = w / s;
				ch = cw / s;
			}
			else if (s > cs + 0.2) {
				s = cs + 0.2;
				var n = h * s;
				x = (w - n) / 2;
				w = n;
				cw = ch * s;
			}
			if (cw > w) {
				cw = w;
				ch = cw / s;
			}
			if (ch > h) {
				ch = h;
				cw = ch * s;
			}
			return { w: w, h: h, cw: cw, ch: ch, x: x, y: 0 };
		}
		function deal1(img) {
			var wh = calc(img.width, img.height);
			var cv = document.createElement("canvas");
			cv.width = wh.cw;
			cv.height = wh.ch;
			try {
				var ctx = cv.getContext("2d");
				ctx.drawImage(img, wh.x, wh.y, wh.w, wh.h, 0, 0, wh.cw, wh.ch);
			}
			catch (ex) { callback(); }
			deal2(cv);
		}
		function deal2(cvs) {
			var ms = (option.size || 1000) * 1024;
			var n = 1.0;
			var b64 = cvs.toDataURL(imgMime, 0.85);
			if (!b64) { callback(); return; }
			$$.BlobToUrl(b64, imgMime, function (url) {
				callback(url);
			})
		}

		$$.BlobToUrl(file, imgMime, function (url) {
			if (!url) callback();
			else if (file.size > 10 && file.size < 80000) callback(url);
			else {
				var img = new Image();
				img.crossOrigin = "Anonymous";
				img.onerror = function () { callback(); };
				img.onload = function () { deal1(img); }
				img.src = url;
			}
		});
	}

	//从手机拍照获取图片
	//与SelImg使用相同
	me.CameraImg = function (callback, option) { if (callback) callback(); };

	//从手机选择图片
	//option 图片处理属性，包含
	//width：宽度，0表示不限，默认600
	//height：高度，0表示不限，默认0
	//mime：选择类型，默认image/*
	//size：最大文件大小，单位K，默认1000
	//temp：暂时保存本地，true/false，默认false
	//-------
	//callback ，选择的回调函数 function(rst)
	//rst 返回本地图片地址
	me.SelImg = function (callback, option, file) {
		if (!callback) callback = emptyfunc;
		if (!file || file.size < 10) { callback(); return;}
		dealImage(file, option, function (url) {
			if (url) callback({ url: url });
			else callback();
		});
	};
	//从手机选择多个图片
	//与SelImg使用相同
	//区别是返回urls数组
	me.SelImgs = function (callback, option, files) {
		if (!callback) callback = emptyfunc;
		if (!files || files.length < 1) { callback(); return; }
		if (files.length > 10) { $$.Tips("最多选择10张图片"); callback(); return; }
		var urls = [], idx = 0;
		function exec() {
			if (idx >= files.length) {
				if (urls.length > 0) callback({ urls: urls });
				else callback();
				return;
			}
			var file = files[idx++];
			if (!file || file.size < 10) { exec(); return; }
			dealImage(file, option, function (url) {
				if (url) urls.push(url);
				exec();
			});
		}
		exec();
	};

	function upImage(fdata, subdir, callback) {
		var called = false;
		var url = $$.UploadUrl + "ext=jpg&sub=";
		if (subdir) url += subdir;
		$.ajax({
			method: "POST",
			url: url,
			data: fdata,
			dataType: "text",
			processData: false,
			contentType: false,
			success: function (text) {
				called = true;
				var rst = $$.Jsonar.parse(text);
				if (rst && rst.url) callback($$.UploadHost + rst.url);
				else callback();
			},
			error: function (a, b, err) { called = true; callback(); },
			complete: function () { if (!called) callback(); },
			async: true,
			global: false
		});
	}
	//上传图片
	//uri：本地图片url
	//-------
	//callback ，上传的回调函数 function(rst)
	//rst 返回结果对象，包括
	//success：是否成功
	//url： 网络图片地址
	//mess： 输出消息
	me.UpImg = function (uri, callback, subdir) {
		if (!callback) callback = emptyfunc;
		if (!uri || uri.length < 3) { callback(); return; }
		$$.UrlToBlob(uri, imgMime, function (blob) {
			if (!blob) { callback(); return; }
			var fdata = new FormData();
			fdata.append("file", blob, "1.jpg");
			upImage(fdata, subdir, function (url) {
				if (!url) callback();
				else callback({ success: true, url: url, size:blob.size });
			});
		});
	};
	//上传多个图片
	//uris：本地图片地址数组
	//-------
	//callback ，上传的回调函数 function(rst)
	//rst 返回结果对象，包括
	//success：是否成功
	//urls： 网络图片地址数组
	//mess： 输出消息
	me.UpImgs = function (uris, callback, subdir) {
		if (!callback) callback = emptyfunc;
		if (!uris || uris.length < 1) { callback(); return; }
		var idx = 0, urls = [];
		function exec() {
			if (idx >= uris.length) {
				if (urls.length > 0) callback({ success: true, urls: urls });
				else callback();
				return;
			}
			var uri = uris[idx++];
			if (!uri) { exec(); return; }
			$$.UrlToBlob(uri, imgMime, function (blob) {
				if (!blob) { exec(); return; }
				var fdata = new FormData();
				fdata.append("file", blob, "1.jpg");
				upImage(fdata, subdir, function (url) {
					if (url) urls.push({ url: url, size: blob.size });
					exec();
				});
			});
		}
		exec();
	};

	me.SaveImgB64 = function (b64, name, callback) { if (callback) callback(); };

    //支付宝支付
    //BillType:4=支付宝,3=账户余额,12=微信
    //Order：订单编号
    //UseTubi: 是否使用兔币, 布尔值
    //Price: 金额, 可选
    //repay:正常支付0，继续支付1
	me.Alipay = function (order, usetubi, BillType, Price, repay, callback) {
	    //callback({ memo: "请安装任务兔APP后再付款" }); return;
	    var tmp = { 'Order': order, 'UseTubi': usetubi, BillType: BillType, 'return_url': '/ext/alipaysucc.html', repay: repay };
	    if(Price){
	        tmp.Price = Price;
	    }
	    
	    $$.GetData('alipay/paylink', tmp, function (rst) {
			if (!rst) rst = {};
			if (!rst.success) {
				callback({ memo: "初始化支付出错" });
				return;
			}
			if (!rst.row || !rst.row.Url) {
			    callback();
			    return;
			}
			$$.Page.Open("pub_viewlink1", { title: "交易详情", src: rst.row.Url }, callback);
		});
	};
    //支付宝认证
	me.Renzheng = function (callback) {
	    $$.GetData('alipay/renzhenglink', {}, function (rst) {
	        if (!rst) rst = {};
	        if (!rst.success) {
	            callback({ memo: "初始化出错" });
	            return;
	        }
	        if (!rst.row || !rst.row.Url) {
	            callback();
	            return;
	        }
	        $$.Page.Open("pub_viewlink1", { title: "支付宝认证", src: rst.row.Url }, callback);
	    });
	};

	//拨打电话
	me.DialPhone = function (phone, fromid, toid) {
		if (!phone) {
			$$.Tips("请安装任务兔APP后再拨打电话");
			return;
		}
		$$.Vis.IsLogon(true, function (rst) {
			if (rst === true) window.open("tel:" + phone);
		});
	};

	//拨打用户电话
	me.DialID = function (fromid, toid) { $$.Tips("请安装任务兔APP后再拨打电话"); };

	//拨打B2C电话
	me.DialB2C = function (fromid, toid) {
		toid = $$.ParseInt(toid);
		if (!toid || toid < 400000 || toid >= 500000) {
			$$.Tips("请安装任务兔APP后再拨打电话");
			return;
		}
		$$.Vis.IsLogon(true, function (rst) {
			if (rst === true) $$.GetSver(toid, function (sver) {
				if (!sver || !sver.Service || !sver.Service.Mobile) {
					$$.Tips("请安装任务兔APP后再拨打电话");
					return;
				}
				window.open("tel:" + sver.Service.Mobile);
			});
		});
		
	};

	//打开外部链接
	me.OpenLink = function (url, titlebar) { if (url) window.open(url); };

	//浏览器打开外部链接
	me.OpenBrowser = function (url) { if (url) window.open(url); };

	//复制到剪贴板
	//callback(rst)	rst:true/false
	var inpCopy = null;
	me.Copy2Clip = function (txt, callback) {
		function exec() {
			if (!inpCopy) inpCopy = $("<input>").addClass("CopyBy").val(txt).appendTo(document.body || document.documentElement)[0];
			if (!inpCopy) return false;
			try {
				inpCopy.select();
				if (document.execCommand("copy", false, false) === true) return true;
			}
			catch(e){}
			return false
		}
		if (!callback) callback = emptyfunc;
		if (!txt) { callback(); return; }
		txt += "";
		var rst = true;
		if (window.copy) window.copy(txt);
		else if (window.clipboardData) window.clipboardData.setData("Text", txt);
		else if (document.execCommand) rst = exec();
		else rst = false;
		callback(rst);
	};

	//判断是否存在第三方app
	//浏览器不支持
	me.AppHas = function (appid, callback) {
		if (callback) callback(false);
	};

	//判断是否存在多个第三方app
	//浏览器不支持
	me.AppHass = function (appid, callback) {
		if (callback) callback(false);
	};

	//打开第三方app
	//浏览器不支持
	me.AppOpen = function (appid, callback) {
		if (callback) callback(false);
	};

	//判断没有越狱
	//回调callback(rst)
	//rst == true 未越狱
	me.Jailin = function (appid, callback) {
		if (callback) callback(true);
	};


	//显示本地推送通知
	//text：推送正文
	//title：推送标题
	//icon：图标url，尽量使用https
	//cata：推送分类，Int，分类相同的通知可能会折叠在一起
	me.SendNotify = function (text, title, icon, cata) {
		if (!text) return;
		if (title) text = "<b>" + title + "</b><br/>" + text;
		$$.Tips(text, 3, true, 0, true);
	};

	//SNS分享
	me.ShareSNS = function (target, params, callback) { if (callback) callback(-99); };
	//SNS授权
	me.AuthSNS = function (target, callback, params) { if (callback) callback(-99); };
	//SNS解除授权
	me.UnAuthSNS = function (target, callback) { if (callback) callback(-99); };

	me.PubKey = function (callback) {
	    var key = '4f37456276f26fa630a9849f9b1711df';
	    if (callback) callback(key);
	};

	me.IMStart = function (params) { };
	me.IMLogout = function () { };
	//me.IMCurUser = function (uid) {};
	me.IMSendMsg = function (msg, callback) { if (callback) callback(); };
};